<template>
  <div>
    <!-- 头部搜索区 -->
    <el-card style="height: calc(100vh - 240px);">
      <template #header>
        <div class="card-header">
          <div class="header">
            <div style="margin-right: 50px">
              <span style="margin-right: 10px;color: gray;">角色名称</span>
              <el-input style="width: 240px" placeholder="请输入角色名称" v-model="searchParams.keywords" />
            </div>
            <div class="block" style="margin-right: 50px">
              <span style="margin-right: 10px;color: gray;">创建时间</span>
              <el-date-picker v-model="value2" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
                @change="handleDateChange" />
            </div>
            <el-button type="primary" @click="getPageData">搜索
              <template #icon>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-button>
            <el-button @click="resetSearchParams">重置
              <template #icon>
                <el-icon>
                  <RefreshRight />
                </el-icon>
              </template>
            </el-button>
          </div>
        </div>
      </template>

      <template #default>
        <div>
          <!-- 操作按钮区 -->
          <div>
            <el-button type="primary" plain @click="addItemHandler()">新增
              <template #icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
            </el-button>
            <el-button type="danger" plain @click="deleteSelectedStudents()">删除
              <template #icon>
                <el-icon>
                  <Delete />
                </el-icon>
              </template>
            </el-button>
          </div>
          <!-- 信息渲染区 -->
          <el-table ref="multipleTableRef" :data="tableData" style="width: 100%;"
            @selection-change="handleSelectionChange" stripe size="large" fit>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="角色ID" width="150" />
            <el-table-column prop="name" label="角色名称" width="150" />
            <el-table-column prop="code" label="角色编码" width="150" />
            <el-table-column prop="status" label="角色状态" width="150" :formatter="statusFormatter" />
            <el-table-column fixed="right" label="操作" min-width="150" />
            <el-table-column prop="updateTime" label="更新时间" width="220" />
            <el-table-column label="操作" fixed="right">
              <!-- !使用 #default="{ row }" 来定义默认插槽，并将当前行的数据对象作为 row 变量传递给插槽内容。 -->
              <template #default="{ row }">
                <el-button link type="primary" size="large" @click="editItemHandler(row)">修改</el-button>
                <el-button link type="danger" size="large" @click="delItemHadler(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>
        <div class="mypage">
          <el-pagination background layout="prev, pager, next" :total="pageParams.total" @change="pageChangeHandler" />
        </div>
      </template>
    </el-card>
    <!-- ----------------------------------------添加按钮弹窗------------------------------------------ -->
    <el-dialog v-model="dialogFormVisible" :title="ruleFormInfo.title" width="800">
      <RoleForm ref="ruleFormRef" :form-data="ruleForm" :disabled="isSBtnDisable" :loading="isSBtnLoding"
        :submitForm="submitForm"></RoleForm>
    </el-dialog>
  </div>
</template>

<script lang='ts'>
export default {
  name: 'cyara',
}
</script>

<script lang='ts' setup>
import { onMounted, ref, useTemplateRef } from 'vue'
import { type RolesType, requestGetRolesPage, addRole, editRole, delRole } from '@/service/utils'
import { ElMessage, ElMessageBox, type FormInstance, type TableInstance } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-message-box.css'
import RoleForm from './conpent/cyaraForm.vue'
import { isObject } from 'lodash'

/*-------------------------------------------请求数据变量容器---------------------------------------- */
const tableData = ref<RolesType[]>()

/*-------------------------------------------请求角色数据参数设置---------------------------------------- */
const pageParams = ref({
  pageNum: 1, //当前页
  pageSize: 15, //每页数量
  total: 0,
})
/*-------------------------------------------搜索框关键字---------------------------------------- */
const searchParams = ref({
  keywords: '',
  startDate: '',
  endDate: '',
})

/*-------------------------------------------控制是否显示弹窗布尔值---------------------------------------- */
const dialogFormVisible = ref(false)
const isSBtnLoding = ref(false)
const isSBtnDisable = ref(false)
const ruleFormRef = useTemplateRef('ruleFormRef')

const ruleForm = ref<RolesType>({
  code: '',
  createTime: '',
  name: '',
  sort: 1,
  status: 1,
})

/*-------------------------------------------判断添加与修改关键字---------------------------------------- */
const ruleFormInfo = ref<{ type: 'add' | 'edit'; title: string }>({
  type: 'add',
  title: '添加数据',
})

/*-------------------------------------------提交表单:@param formEl表单组件对象---------------------------------------- */
const submitForm = async (formEl: FormInstance | undefined) => {
  isSBtnLoding.value = true
  isSBtnDisable.value = true
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res
      try {
        ruleForm.value.id = Number(ruleForm.value.id)
        // 添加操作
        if (ruleFormInfo.value.type === 'add') {
          // http请求
          res = await addRole(ruleForm.value)
        }
        //修改操作
        if (ruleFormInfo.value.type === 'edit') {
          // http请求
          res = await editRole(String(ruleForm.value.id), ruleForm.value)
        }
        if (res!.code !== '2000') {
          throw new Error(isObject(res?.msg) ? (res.msg as { Message: string })?.Message : res?.msg)
        }
        ElMessage.success(ruleFormInfo.value.type === 'add' ? `添加成功` : `修改成功`)
        getPageData()
      } catch (error: unknown) {
        if (error instanceof Error) {
          ElMessage.error(error.message)
        } else {
          ElMessage.error('未知错误')
        }
      } finally {
        isSBtnLoding.value = false
        isSBtnDisable.value = false
        // 关闭模态框
        dialogFormVisible.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/*-------------------------------------------get请求获取分页数据---------------------------------------- */
const getPageData = async () => {
  const resRoles = await requestGetRolesPage({
    // 分页参数
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize,
    // 检索的参数
    ...searchParams.value,
  })
  console.log(resRoles.data)
  tableData.value = resRoles.data.list
  pageParams.value.total = resRoles.data.total
}

/*-------------------------------------------post请求添加数据---------------------------------------- */
const addItemHandler = async () => {
  //显示弹窗
  dialogFormVisible.value = true
  // 重置表单数据
  ruleForm.value = JSON.parse(
    JSON.stringify({
      code: '',
      createTime: '',
      name: '',
      sort: 1,
      status: 1,
    }),
  )
  ruleFormInfo.value = {
    type: 'add',
    title: '添加角色',
  }
  ruleFormRef.value?.reset()
}

/*-------------------------------------------put修改角色数据---------------------------------------- */
const editItemHandler = (row: RolesType) => {
  dialogFormVisible.value = true
  ruleFormInfo.value = {
    type: 'edit',
    title: '修改角色',
  }
  // 重置：填充表单
  ruleForm.value = JSON.parse(JSON.stringify(row))
  ruleFormRef.value?.reset()
}
/*-------------------------------------------delete删除角色---------------------------------------- */
const delItemHadler = (row: RolesType) => {
  ElMessageBox.confirm('确认删除?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await delRole(`${row.id}`)
        if (res.data.code !== '2000') {
          throw new Error(res.data.msg)
        }
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getPageData()
      } catch (error: unknown) {
        if (error instanceof Error) {
          ElMessage({
            type: 'error',
            message: error.message,
          })
        } else {
          ElMessage.error('未知错误')
        }
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/*-------------------------------------------挂载阶段自动获取角色信息---------------------------------------- */
onMounted(() => {
  getPageData()
})
/*-------------------------------------------分页事件---------------------------------------- */
const pageChangeHandler = (currentPage: number, pageSize: number) => {
  pageParams.value.pageNum = currentPage
  pageParams.value.pageSize = pageSize
  getPageData()
}
/*-------------------------------------------转化用户状态的方法---------------------------------------- */

const statusFormatter = (row: RolesType, column: unknown, cellValue: number) => {
  if (cellValue === 1) return '正常'
  if (cellValue === 0) return '停用'
  return '未知'
}

//全选
// 定义一个响应式引用，用于存储表格实例
const multipleTableRef = ref<TableInstance>()
// 定义一个响应式引用，用于存储选中的角色数组
const multipleSelection = ref<RolesType[]>([])

// 定义一个函数，用于处理表格选中项变化事件
const handleSelectionChange = (val: RolesType[]) => {
  // 将选中的角色数组赋值给响应式引用
  multipleSelection.value = val
}

/*-------------------------------------------删除选中的角色的方法---------------------------------------- */
// 定义一个异步函数，用于删除选中的角色
const deleteSelectedStudents = async () => {
  // 如果没有选中任何角色，则提示用户选择要删除的角色
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的角色',
    })
    return
  }

  // 弹出确认框，询问用户是否确认删除选中的角色
  ElMessageBox.confirm('确认删除选中的角色?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 将选中的角色逐个删除
        const promises = multipleSelection.value.map(ruleForm => delRole(`${ruleForm.id}`))
        // 等待所有删除操作完成
        await Promise.all(promises)
        // 删除成功后，提示用户删除成功
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        // 刷新页面数据
        getPageData()
      } catch (error: unknown) {
        // 如果删除过程中出现错误，则提示用户错误信息
        if (error instanceof Error) {
          ElMessage({
            type: 'error',
            message: error.message,
          })
        } else {
          // 如果错误不是Error类型，则提示未知错误
          ElMessage.error('未知错误')
        }
      }
    })
    .catch(() => {
      // 如果用户取消删除，则提示用户取消删除
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


/*-------------------------------------------修改选中用户的方法---------------------------------------- */
const Scdelete = (row: RolesType) => {
  // 如果选中的角色大于2个，则提示用户只能选择一个角色进行修改
  if (multipleSelection.value.length !== 1) {
    ElMessage({
      type: 'warning',
      message: '只能选择一个角色进行修改',
    })
    return
  }
  dialogFormVisible.value = true
  ruleFormInfo.value = {
    type: 'edit',
    title: '修改角色',
  }
  // 重置：填充表单
  ruleForm.value = JSON.parse(JSON.stringify(row))
  ruleFormRef.value?.reset()
}

/*-------------------------------------------根据更新时间来搜索的方法---------------------------------------- */
//绑定时间的响应式变量
const value2 = ref<[Date, Date] | any>(null);

// 定义一个处理日期变化的函数，接收一个日期数组或null作为参数
const handleDateChange = (dates: [Date, Date] | null) => {
  // 检查传入的dates是否为非空
  if (dates) {
    // 获取开始日期和结束日期
    const startDate = dates[0];
    const endDate = dates[1];
    // 将开始日期格式化为YYYY-MM-DD的字符串，并赋值给searchParams的startDate属性
    searchParams.value.startDate = `${startDate.getFullYear()}-${startDate.getMonth() + 1}-${startDate.getDate()}`;
    // 将结束日期格式化为YYYY-MM-DD的字符串，并赋值给searchParams的endDate属性
    searchParams.value.endDate = `${endDate.getFullYear()}-${endDate.getMonth() + 1}-${endDate.getDate()}`;
  } else {
    // 如果dates为空，则将searchParams的startDate和endDate属性重置为空字符串
    searchParams.value.startDate = '';
    searchParams.value.endDate = '';
  }
};



// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value.keywords = '';
  searchParams.value.startDate = '';
  searchParams.value.endDate = '';
  value2.value = null;
  getPageData();
}





</script>

<style lang='scss' scoped>
.header {
  display: flex;
  margin-bottom: 30px;
}

.modal {
  // display: none;
  position: fixed;
  z-index: 10;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);

  .modal-content {
    background-color: #fff;
    margin: 5% auto;
    padding: 20px;
    border-radius: 4px;
    width: 400px;

    .modalTitle {
      margin-bottom: 20px;
      font-size: 20px;
      text-align: center;
    }
  }
}
</style>
